﻿using System;
using Autofac;
using System.IO;
using System.Web;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using Autofac.Integration.Web.Mvc;

namespace GBlog.Core
{
    internal static class RegisterServices
    {
        internal static void LoadAssemblies(ContainerBuilder builder)
        {
            string path = HttpRuntime.BinDirectory;
            DirectoryInfo directory = new DirectoryInfo(path);
            FileInfo[] files = directory.GetFiles("GBlog.*.dll", SearchOption.TopDirectoryOnly);
            foreach (FileInfo file in files)
            {
                if (file.Name == "GBlog.Core.dll")
                {
                    continue;
                }
                AssemblyName assemblyName = AssemblyName.GetAssemblyName(file.FullName);
                Assembly assembly = AppDomain.CurrentDomain.Load(assemblyName);
                builder.RegisterControllers(assembly).PropertiesAutowired();
            }
        }

        internal static void RegisterAll(ContainerBuilder builder)
        {
            List<Type> types = new List<Type>();
            foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
            {
                IEnumerable<Type> type = a.GetTypes().Where(t => typeof(IGRegister).IsAssignableFrom(t) && !t.IsInterface);
                types.AddRange(type);
            }

            foreach (Type t in types)
            {
                IGRegister register = (IGRegister)Activator.CreateInstance(t);
                register.RegisterServices(builder);
            }
        }
    }
}